<template>
  <div class="system-menu-container">
		<div class="system-user-search mb15">
			<el-form :model="param" :inline="true" ref="queryFormRef" @keyup.enter.native="loadList" label-width="120px">
				<el-row>
					<el-col :span="8">
						<el-form-item prop="authId" label="授权人">
							<el-input v-model="param.authId" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item prop="beAuthId" label="被授权人">
							<el-input v-model="param.beAuthId" clearable ></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div class="home_common background_bg6">
			<div class="btnStyle">
				<el-button  type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
				<el-button type="primary"  icon="ele-Edit"  @click="updateHandle()" :disabled="dataListSelections.length !== 1">修改</el-button>
				<el-button type="danger"  icon="ele-Delete"  @click="deleteHandle()" :disabled="dataListSelections.length <= 0">删除</el-button>
			</div>
		</div>
		<el-table :data="dataList" border v-loading="listLoading" @selection-change="selectionChangeHandle" style="width: 100%;">
			<el-table-column prop="id" type="selection" width="50"></el-table-column>
			<el-table-column prop="authName" label="授权人" width="150"></el-table-column>
			<el-table-column prop="beAuthName" label="被授权人" width="150"></el-table-column>
			<el-table-column prop="authCatagory" width="135" label="控制类别" column-key="1121" :formatter="formatStatus"></el-table-column>
			<el-table-column prop="startTime" width="135" label="开始时间" :formatter="formatDate"></el-table-column>
			<el-table-column prop="endTime" width="135" label="结束时间"></el-table-column>
			<el-table-column prop="reason" label="委托原因"></el-table-column>
			<el-table-column  width="150" label="操作">
				<template  #default="scope">
					<el-button type="primary" link @click="updateHandle(scope.row.id)" >修改</el-button>
					<el-button type="primary" link @click="deleteHandle(scope.row.id)" >删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			@size-change="onHandleSizeChange"
			@current-change="onHandleCurrentChange"
			:pager-count="5"
			:page-sizes="[10, 50, 200]"
			v-model:current-page="param.page"
			background
			v-model:page-size="param.limit"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total" small>
		</el-pagination>
		<el-dialog :title="!dataForm.id ? '新增' : '修改'" v-model="dialogVisible" width="600px" class="customDialog" :close-on-click-modal="false">
			<el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmit(dataFormRef)" label-width="120px">
				<el-form-item label="控制类别" prop="authCatagory">
					<DicSelect v-model="dataForm.authCatagory" placeholder="请选择" dicCode="1121" style="width:100%"></DicSelect>
				</el-form-item>
				<el-form-item label="委托原因" prop="reason">
					<el-input v-model="dataForm.reason" placeholder="委托原因" style="width:100%"></el-input>
				</el-form-item>
				<el-form-item label="授权人" prop="authId">
					<el-select v-model="dataForm.authId" clearable filterable placeholder="授权人" style="width:100%">
						<el-option v-for="user in userList" :key="user.id" :label=user.staffName :value="user.id"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="被授权人" prop="beAuthId">
					<el-select v-model="dataForm.beAuthId" clearable filterable placeholder="被授权人" style="width:100%">
						<el-option v-for="user in userList" :key="user.id" :label=user.staffName :value="user.id" ></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="开始时间" prop="startTime">
					<el-date-picker v-model="dataForm.startTime" type="date" placeholder="起始时间" value-format="YYYY-MM-DDTHH:mm:ss" style="width:100%"/>
				</el-form-item>
				<el-form-item label="结束时间" prop="endTime">
					<el-date-picker v-model="dataForm.endTime" type="date" placeholder="结束时间"  value-format="YYYY-MM-DDTHH:mm:ss" style="width:100%"/>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose(dataFormRef)">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(dataFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, defineComponent } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {workflowApi} from '/@/api/workflowapi'
import { getCodeList } from '/@/utils/cacheDict'
import {systemApi} from '/@/api/systemapi'
export default defineComponent({
	setup () {
		const dataFormRef = ref<FormInstance>()
		const queryFormRef = ref<FormInstance>()
		const userQueryFormRef = ref<FormInstance>()
		const state = reactive({
			isShow: false,
			listLoading: false,
			dataList: [],
			total: 0,
			userTotal: 0,
			totalSelect: 0,
			param: {
				page: 1,
				limit: 10,
				authId: '',
				beAuthId: ''
			},
			dataListSelections: [],
			dialogVisible: false,
			dataDictionaryList: {},
			src2: '',
			assigneeVisible: false,
			userListLoading: false,
			dataForm: {
				id: '',
				authId: '',
				beAuthId: '',
				authCatagory: '',
				startTime: '',
				endTime: '',
				reason: '',
				isEntrust:false
			},
			userList: [],
			checkProcessId: '',
			dataRule: {
				authCatagory: [
				{ required: true, message: "控制类别不能为空", trigger: "blur" }
				],
				authId: [{ required: true, message: "授权人", trigger: "blur" }],
				beAuthId: [
				{ required: true, message: "被授权人不能为空", trigger: "blur" }
				],
				startTime: [
				{ required: true, message: "开始时间不能为空", trigger: "blur" }
				],
				endTime: [
				{ required: true, message: "结束时间不能为空", trigger: "blur" }
				]
			}
		})

		// 页面加载时
		onMounted(() => {
			// 数据字典
			getCodeList(state, ['1121'])
			getUsers()
			// 列表查询
			loadList()
		})

		//查询
		const loadList = () => {
			state.listLoading = true
			workflowApi().queryDelegationList(state.param).then(data => {
				if (data && data.code === 0) {
					state.dataList = data.page.list
					state.total = data.page.totalCount
				} else {
					state.dataList = []
					state.total = 0
				}
			}).catch(() => {
			}).finally(() => {
				state.listLoading = false
			})
		}
		//重置
		const reSetForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.param.page = 1
			loadList()
		}

		// 分页改变
		const onHandleSizeChange = (val: number) => {
			state.param.limit = val;
			loadList()
		}
		// 分页改变
		const onHandleCurrentChange = (val: number) => {
			state.param.page = val;
			loadList()
		}
		// 获取用户
		const getUsers = () => {
			systemApi().getAllUserByTenantId().then(data => {
				state.userList = data;
			})
		}

		//新增
		const addOrUpdateHandle = () => {
			state.dialogVisible = true
			state.dataForm = {
				id: '',
				authId: '',
				beAuthId: '',
				authCatagory: '',
				startTime: '',
				endTime: '',
				reason: '',
				isEntrust:false
			}
		}

		const formatStatus = (row:any, column:any, cellValue:any, index:number) => {
			if(Object.keys(state.dataDictionaryList).length>0){
				if (cellValue) {
					return state.dataDictionaryList[column.columnKey][cellValue];
				}
			}
		}
		const selectionChangeHandle = (val: any) => {
			state.dataListSelections = val
		}
		// 修改
		const updateHandle = (id:string | undefined) => {
			state.dialogVisible = true
			if(!id){
				state.dataForm.id = state.dataListSelections[0].id
			}else{
				state.dataForm.id = id
			}
			workflowApi().queryDelegationInfoById(state.dataForm.id).then((data) => {
				if (data && data.code === 0) {
					state.dataForm.id = data.delegation.id
					state.dataForm.authId = data.delegation.authId
					state.dataForm.beAuthId = data.delegation.beAuthId
					state.dataForm.authCatagory = data.delegation.authCatagory
					state.dataForm.startTime = data.delegation.startTime
					state.dataForm.endTime = data.delegation.endTime
					state.dataForm.reason = data.delegation.reason
				}
            })
			
		}
		//取消修改
		const handleClose = (formEl: FormInstance | undefined) => {
			state.dialogVisible = false
			if (formEl){
				formEl.resetFields()
			}
			loadList()
		}
		//提交
		const dataFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					const loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					if (!state.dataForm.id) {
						//新增
						workflowApi().AddDelegation(state.dataForm).then(data => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								loadList()
								state.dialogVisible = false
								formEl.resetFields()
							}else{
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}else{
						//修改
						workflowApi().updateDelegation(state.dataForm).then(data => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								loadList()
								state.dialogVisible = false
								formEl.resetFields()
							}else{
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}
				}
			})
		}
		// 删除
		const deleteHandle = (id: string | undefined) => {
			ElMessageBox.confirm('是否确定删除', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				var ids = id ? [id] : state.dataListSelections.map(item => {
					return item.id
				})
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				workflowApi().delegationDeleteById(ids).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功！')
						loadList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('删除失败！')
				}).finally(() => {
					loading.close()
				})
			})
		}
		return {
			loadList,
			reSetForm,
			onHandleSizeChange,
			onHandleCurrentChange,
			dataFormRef,
			queryFormRef,
			formatStatus,
			addOrUpdateHandle,
			selectionChangeHandle,
			userQueryFormRef,
			updateHandle,
			getUsers,
			handleClose,
			dataFormSubmit,
			deleteHandle,
			...toRefs(state),
		}
	}
})
</script>

<style>

</style>